﻿using System.Configuration;
using System.Reflection;
using System.Web;
using CID.Web.Support.TemplateContentEdition;

namespace CID.Web.Support.Configuration.TemplateContentEdition
{
    public class TemplateContentEditionConfiguration : ConfigurationElement
    {
        private const string TemplateContentEditorViewsBasePathAttibute = "templateContentEditorViewsBasePath";
        private const string BinaryConverterAssembliesElement = "inspectAssembliesForBinaryConverters";

        [ConfigurationProperty(TemplateContentEditorViewsBasePathAttibute)]
        public string TemplateContentEditorViewsBasePath 
        {
            get { return (string) this[TemplateContentEditorViewsBasePathAttibute]; }
        }

        [ConfigurationProperty(BinaryConverterAssembliesElement, IsDefaultCollection = false)]
        [ConfigurationCollection(typeof(BinaryConverterAssemblyConfigurationCollection), AddItemName = "add", ClearItemsName = "clear", RemoveItemName = "remove")]
        public BinaryConverterAssemblyConfigurationCollection BinaryConverterAssemblies
        {
            get { return (BinaryConverterAssemblyConfigurationCollection)this[BinaryConverterAssembliesElement]; }
        }

        internal void Configure(TemplateContentEditorRegistry registry)
        {
            PartialViewUserInterfaceDefinition.TemplateContentEditionViewsBasePath = TemplateContentEditorViewsBasePath;
            registry.TemplateContentEditorViewsBasePath = HttpContext.Current.Server.MapPath(TemplateContentEditorViewsBasePath);
            foreach (BinaryConverterAssemblyConfiguration binaryConverterAssembly in BinaryConverterAssemblies)
            {
                var assembly = Assembly.Load(binaryConverterAssembly.AssemblyName);
                registry.RegisterAssemblyToInspectForBinaryContentConverters(assembly, binaryConverterAssembly.SpecificVersion);
            }
        }
    }
}